package com.indexingsystem.system.oauth2;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration.Password;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.indexingsystem.boss.entity.Pusers;
import com.indexingsystem.boss.entity.User;
import com.indexingsystem.boss.entity.UserRole;
import com.indexingsystem.system.service.IPusersService;
import com.indexingsystem.system.service.IUserInfosService;
import com.indexingsystem.system.service.IUserRoleService;

public class CpwlUserDetailsService implements UserDetailsService {

	@Autowired
	JdbcTemplate jdbcTemplate;
	@Autowired
	private IPusersService iPusersService;
	@Autowired
	private  IUserRoleService iUserRoleService;
	private final String sqlLoadUser;
	private final String sqlLoadAuthorities;
	private final RowMapper<User> myUserDetailsRowMapper;
	private final RowMapper<GrantedAuthority> authorityRowMapper;

	private static Logger logger = LoggerFactory.getLogger(CpwlUserDetailsService.class);

	
	
	public CpwlUserDetailsService() {
		   super();  
	        sqlLoadUser = "SELECT user_id,user_name,password  FROM dh_users WHERE user_name=? ";  
	        sqlLoadAuthorities = "";  //SELECT authority FROM view_role WHERE username=?
	        myUserDetailsRowMapper = new RowMapper<User>() {  
	            @Override  
	            public User mapRow(ResultSet rs, int rowNum) throws SQLException {  
	                return new User(rs.getString(1), rs.getString(2),rs.getString(3));  
	            }  
	        };  
	        authorityRowMapper = new RowMapper<GrantedAuthority>() {  
	            @Override  
	            public GrantedAuthority mapRow(ResultSet rs, int rowNum)  
	                    throws SQLException {  
	                return new SimpleGrantedAuthority(rs.getString(2));  
	            }  
	        }; 
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String url=request.getServletPath().toString();
		System.out.println(url);
		String password = request.getParameter("password");
		
		/*final DhUsers dhUsers=this.dhUsersService.getDhUsers("004e3318c36746de85fb28b2108d9c09");*/
	/*	GrantedAuthority authority = new SimpleGrantedAuthority("Admin");*/
		/* Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>(); 
		 auths.add(authority);*/
		/*UserDetails userDetails = (UserDetails)new UserDetails(dhUsers.getUserName(), 
				dhUsers.getPassword(),"",true,auths);
		return userDetails;*/
		
/*		return new UserDetails() {
			
			private static final long serialVersionUID = 2059202961588104658L;

			@Override
			public boolean isEnabled() {
				return true;
			}
			
			@Override
			public boolean isCredentialsNonExpired() {
				return true;
			}
			
			@Override
			public boolean isAccountNonLocked() {
				return true;
			}
			
			@Override
			public boolean isAccountNonExpired() {
				return true;
			}
			
			@Override
			public String getUsername() {
				return dhUsers.getUserName();
			}
			
			@Override
			public String getPassword() {
				return dhUsers.getPassword();
			}
			
			@Override
			public Collection<? extends GrantedAuthority> getAuthorities() {
				List<SimpleGrantedAuthority> auths = new java.util.ArrayList<SimpleGrantedAuthority>();
				auths.add(new SimpleGrantedAuthority("ROLE_OAUTH_CLIENT"));
				return auths;
			}
		};
		*/
		try {  
           Pusers userFromQuery =iPusersService.getDhUsersByName(username);/* jdbcTemplate.queryForObject(sqlLoadUser,  
                    myUserDetailsRowMapper, username);  */
            //查询用户具备的角色集合
           List<UserRole>  dhUserRoleList= iUserRoleService.getDhUserRoleList(userFromQuery.getUserId());
           Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();  
           if(null!=dhUserRoleList&&dhUserRoleList.size()>0) {
        	   for(int i=0;i<dhUserRoleList.size();i++)
        		   auths.add(new SimpleGrantedAuthority(dhUserRoleList.get(i).getRoleId()));
           }else {
        	  /* throw new AccessDeniedException("-------用户没有角色，不能获取token-------");*/
           }
  
            System.out.println(auths.toString()); 
            return new User(userFromQuery.getUserId(), userFromQuery.getUserName(),  
                    userFromQuery.getPassword(), true,  
                    auths);  
        } catch (EmptyResultDataAccessException e) {  
           /* System.out.println("用户名或密码不正确"); */
            throw new UsernameNotFoundException("用户名或密码不正确");  
        }  
	}

}